<template>
  <div class="article-write">
    <div class="write-container">
      <!-- 顶部导航 -->
      <div class="write-header">
        <div class="header-left">
          <a-button type="text" @click="handleBack" :icon="h(ArrowLeftOutlined)"> 返回 </a-button>
        </div>
        <div class="header-center">
          <span class="draft-status" v-if="isDraftSaved">
            <cloud-upload-outlined />
            草稿已保存
          </span>
        </div>
        <div class="header-right">
          <a-button @click="handleSaveDraft" :loading="savingDraft"> 保存草稿 </a-button>
          <a-button type="primary" @click="handlePublish" :loading="publishing">
            {{ isEdit ? '更新文章' : '发布文章' }}
          </a-button>
        </div>
      </div>

      <!-- 文章标题输入 -->
      <div class="title-section">
        <a-input v-model:value="article.title" placeholder="请输入文章标题..." size="large" :bordered="false" class="title-input" :maxlength="100" />
      </div>

      <!-- 文章设置 -->
      <div class="article-settings">
        <a-row :gutter="20" align="middle">
          <a-col :span="7">
            <div class="setting-item">
              <label>分类</label>
              <div class="category-input-group">
                <a-select v-model:value="article.categories" mode="multiple" placeholder="选择分类" :options="categoryOptions" style="flex: 1; max-width: 300px" :max-tag-count="1" />
                <a-button v-if="userStore.username === 'woaichitudouo'" @click="showAddCategoryModal = true" type="dashed" :icon="h(PlusOutlined)" title="新增分类"> 新增 </a-button>
              </div>
            </div>
          </a-col>
          <a-col :span="7">
            <div class="setting-item">
              <label>标签</label>
              <a-select v-model:value="article.tags" mode="tags" placeholder="添加标签" style="width: 100%; max-width: 400px" :max-tag-count="2" :token-separators="[',', ' ']" />
            </div>
          </a-col>
          <a-col :span="10">
            <div class="setting-item">
              <label>封面图片 <span class="preview-tips">读者看到的封面图片</span></label>
              <div class="cover-section">
                <!-- 没有封面时显示上传区域 -->
                <div v-if="!article.coverImage" class="cover-upload-container">
                  <a-upload :file-list="coverFileList" :before-upload="handleBeforeUpload" @change="handleCoverChange" @remove="handleCoverRemove" accept="image/*" :max-count="1" :show-upload-list="false" :loading="uploading">
                    <div class="cover-upload-button">
                      <div class="upload-icon">
                        <picture-outlined v-if="!uploading" />
                        <loading-outlined v-else class="spinning" />
                      </div>
                      <div class="upload-text">
                        <span class="primary-text">{{ uploading ? '上传中...' : '点击上传封面' }}</span>
                        <span class="sub-text">JPG、PNG、GIF ≤ 5MB</span>
                      </div>
                    </div>
                  </a-upload>
                </div>

                <!-- 有封面时显示预览和操作 -->
                <div v-else class="cover-preview-section">
                  <div class="preview-image-container" @click="handleImagePreview" title="点击预览大图">
                    <img :src="getImageUrl(article.coverImage)" alt="封面预览" class="preview-image" />
                    <div class="image-overlay">
                      <a-button type="text" danger @click.stop="handleRemoveCover" :icon="h(DeleteOutlined)" class="remove-button" title="删除封面"> 删除 </a-button>
                    </div>
                  </div>
                  <div class="preview-actions">
                    <a-upload :file-list="[]" :before-upload="handleBeforeUpload" @change="handleCoverChange" accept="image/*" :max-count="1" :show-upload-list="false" :loading="uploading">
                      <a-button type="dashed" :loading="uploading">
                        {{ uploading ? '上传中...' : '更换封面' }}
                      </a-button>
                    </a-upload>
                  </div>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>

      <!-- Markdown 编辑器 -->
      <div class="editor-section">
        <md-editor
          v-model="article.content"
          :preview="true"
          :toolbars="toolbars"
          :theme="editorTheme"
          @upload-img="handleUploadImg"
          @save="handleSave"
          :preview-theme="previewTheme"
          :sanitize="sanitizeHtml"
          placeholder="开始写作吧..."
          :auto-detect-code="true"
          :auto-focus="false"
          :scroll-auto="false"
          autoFoldThreshold="3000"
        />
      </div>

      <!-- 图片预览弹窗 -->
      <a-modal v-model:open="showImagePreview" title="封面预览" width="80%" :footer="null" centered @cancel="showImagePreview = false">
        <div class="image-preview-container">
          <img :src="getImageUrl(article.coverImage)" :alt="article.title || '封面预览'" class="preview-full-image" />
        </div>
      </a-modal>

      <!-- 发布设置弹窗 -->
      <a-modal v-model:open="showPublishModal" title="发布文章" width="600px" @ok="confirmPublish" @cancel="showPublishModal = false" :confirm-loading="publishing" v-if="article.title && article.content">
        <div class="publish-settings">
          <a-form :model="publishForm" layout="vertical">
            <a-form-item label="文章摘要" name="summary">
              <a-textarea v-model:value="publishForm.summary" :rows="4" :maxlength="200" show-count placeholder="不填写将自动从文章内容中提取..." />
            </a-form-item>

            <a-form-item label="发布方式">
              <a-radio-group v-model:value="publishForm.publishType">
                <a-radio value="public">公开发布</a-radio>
                <a-radio value="draft">保存为草稿</a-radio>
              </a-radio-group>
            </a-form-item>

            <div class="article-preview">
              <h3>文章预览</h3>
              <div class="preview-card">
                <div class="preview-title">{{ article.title || '请输入文章标题' }}</div>
                <div class="preview-summary">
                  {{ publishForm.summary || extractPreviewSummary() }}
                </div>
                <div class="preview-meta">
                  <span>{{ userStore.username }}</span>
                  <span>{{ new Date().toLocaleDateString() }}</span>
                  <span v-if="article.tags.length">
                    {{ article.tags.slice(0, 3).join(' · ') }}
                  </span>
                </div>
              </div>
            </div>
          </a-form>
        </div>
      </a-modal>

      <!-- 新增分类弹窗 -->
      <a-modal v-model:open="showAddCategoryModal" title="新增分类" width="400px" @ok="handleAddCategory" @cancel="showAddCategoryModal = false" :confirm-loading="addingCategory">
        <a-form :model="newCategoryForm" layout="vertical">
          <a-form-item label="分类名称" name="name" :rules="[{ required: true, message: '请输入分类名称' }]">
            <a-input v-model:value="newCategoryForm.name" placeholder="请输入分类名称" :maxlength="20" />
          </a-form-item>
          <a-form-item label="分类描述" name="description">
            <a-textarea v-model:value="newCategoryForm.description" placeholder="请输入分类描述（可选）" :rows="3" :maxlength="100" />
          </a-form-item>
          <a-form-item label="排序顺序" name="sort_order">
            <a-input-number v-model:value="newCategoryForm.sort_order" placeholder="数字越小排序越靠前" :min="0" style="width: 100%" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, h, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { ArrowLeftOutlined, CloudUploadOutlined, PictureOutlined, DeleteOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { useUserStore } from '@/stores/user'
import { getToken } from '@/utils/auth'
import { getImageUrl } from '@/utils/image'
import { API_BASE_URL } from '@/utils/api'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const isEdit = computed(() => !!route.params.id)
const isDraftSaved = ref(false)
const editorTheme = ref('light')
const previewTheme = ref('default')

const article = ref({
  title: '',
  content: '',
  coverImage: '',
  categories: [],
  tags: []
})

const publishForm = ref({
  summary: '',
  publishType: 'public'
})

const newCategoryForm = ref({
  name: '',
  description: '',
  sort_order: 0
})

// 编辑器配置
const toolbars = [
  'bold',
  'underline',
  'italic',
  'strikeThrough',
  '-',
  'title',
  'sub',
  'sup',
  'quote',
  'unorderedList',
  'orderedList',
  'task',
  '-',
  'codeRow',
  'code',
  'link',
  'image',
  'table',
  'mermaid',
  'katex',
  '-',
  'revoke',
  'next',
  'save',
  '=',
  'pageFullscreen',
  'fullscreen',
  'preview',
  'previewOnly',
  'htmlPreview',
  'catalog'
]

// 上传相关
const coverFileList = ref([])
const uploading = ref(false)
const savingDraft = ref(false)
const publishing = ref(false)
const showPublishModal = ref(false)
const showImagePreview = ref(false)
const showAddCategoryModal = ref(false)
const addingCategory = ref(false)

// 分类相关
const categories = ref([])
const categoryOptions = computed(() => {
  return categories.value.map((cat) => ({
    label: `${cat.name} (${cat.article_count})`,
    value: cat.name
  }))
})

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await fetch(`${API_BASE_URL}/articles/categories/list`)
    const result = await response.json()

    if (result.code === 200) {
      categories.value = result.data || []
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 新增分类
const handleAddCategory = async () => {
  if (!newCategoryForm.value.name.trim()) {
    message.error('请输入分类名称')
    return
  }

  addingCategory.value = true

  try {
    const response = await fetch(`${API_BASE_URL}/articles/categories`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getToken()}`
      },
      body: JSON.stringify({
        name: newCategoryForm.value.name.trim(),
        description: newCategoryForm.value.description.trim(),
        sort_order: newCategoryForm.value.sort_order || 0
      })
    })
    const result = await response.json()

    if (result.code === 200) {
      message.success('分类创建成功')

      // 重新获取分类列表
      await fetchCategories()

      // 自动选中新创建的分类
      if (!article.value.categories.includes(result.data.name)) {
        article.value.categories.push(result.data.name)
      }

      // 重置表单并关闭弹窗
      newCategoryForm.value = {
        name: '',
        description: '',
        sort_order: 0
      }
      showAddCategoryModal.value = false
    } else {
      message.error(result.msg || '创建分类失败')
    }
  } catch (error) {
    console.error('创建分类失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    addingCategory.value = false
  }
}

// 处理图片预览
const handleImagePreview = () => {
  if (article.value.coverImage) {
    showImagePreview.value = true
  }
}

// 如果是编辑模式，获取文章详情
const fetchArticleDetail = async () => {
  if (!isEdit.value) return

  try {
    const response = await fetch(`${API_BASE_URL}/articles/${route.params.id}`, {
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    })
    const result = await response.json()

    if (result.code === 200) {
      const data = result.data
      article.value = {
        title: data.title,
        content: data.content,
        coverImage: data.cover_image || '',
        categories: data.categories || [],
        tags: data.tags || []
      }

      publishForm.value.summary = data.summary || ''

      // 设置封面图片
      if (data.cover_image) {
        coverFileList.value = [
          {
            uid: '-1',
            name: 'cover.jpg',
            status: 'done',
            url: getImageUrl(data.cover_image)
          }
        ]
      }
    } else {
      message.error(result.msg || '获取文章详情失败')
      router.push('/articles')
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    message.error('网络错误，请稍后重试')
  }
}

// 处理图片上传
const handleUploadImg = async (files, callback) => {
  const uploadPromises = files.map(async (file) => {
    const formData = new FormData()
    formData.append('file', file)

    try {
      const response = await fetch(`${API_BASE_URL}/upload/upload-img`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${getToken()}`
        },
        body: formData
      })
      const result = await response.json()

      if (result.code === 200) {
        return result.data.path
      } else {
        throw new Error(result.msg || '上传失败')
      }
    } catch (error) {
      console.error('图片上传失败:', error)
      message.error('图片上传失败')
      throw error
    }
  })

  try {
    const urls = await Promise.all(uploadPromises)
    callback(urls)
  } catch (error) {
    callback([])
  }
}

// 处理封面上传
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }

  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB!')
    return false
  }

  return false // 阻止自动上传
}

const handleCoverChange = async (info) => {
  const { file } = info

  // 当用户选择文件时，file 就是原始文件对象
  if (file && file.type && file.size) {
    await uploadCoverImage(file)
  }
}

const handleCoverRemove = () => {
  handleRemoveCover()
}

const uploadCoverImage = async (file) => {
  const formData = new FormData()
  formData.append('file', file)

  uploading.value = true

  try {
    const response = await fetch(`${API_BASE_URL}/upload/upload-img`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${getToken()}`
      },
      body: formData
    })
    const result = await response.json()

    if (result.code === 200) {
      article.value.coverImage = result.data.path
      coverFileList.value = [
        {
          uid: file.uid || Date.now(),
          name: file.name,
          status: 'done',
          url: getImageUrl(result.data.path)
        }
      ]
      message.success('封面上传成功')
    } else {
      message.error(result.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    message.error('上传失败，请稍后重试')
  } finally {
    uploading.value = false
  }
}

const handleRemoveCover = () => {
  article.value.coverImage = ''
  coverFileList.value = []
}

// 保存草稿
const handleSaveDraft = async () => {
  if (!article.value.title.trim()) {
    message.warning('请先输入文章标题')
    return
  }

  savingDraft.value = true

  try {
    // 保存到本地存储
    const draftKey = isEdit.value ? `draft_edit_${route.params.id}` : 'draft_new_article'
    const draftData = {
      ...article.value,
      savedAt: new Date().toISOString()
    }
    localStorage.setItem(draftKey, JSON.stringify(draftData))

    isDraftSaved.value = true
    message.success('草稿已保存到本地')

    // 3秒后隐藏提示
    setTimeout(() => {
      isDraftSaved.value = false
    }, 3000)
  } catch (error) {
    console.error('保存草稿失败:', error)
    message.error('保存草稿失败')
  } finally {
    savingDraft.value = false
  }
}

// 编辑器保存快捷键
const handleSave = () => {
  handleSaveDraft()
}

// HTML 清理函数 - 处理预览区域的图片地址
const sanitizeHtml = (html) => {
  // 处理图片地址拼接
  return html.replace(/<img([^>]*?)src=["']([^"']*?)["']([^>]*?)>/gi, (match, before, src, after) => {
    // 如果图片地址不是完整的 URL 且不是 base64 数据，则使用 getImageUrl 处理
    let processedSrc = src
    if (!src.startsWith('http://') && !src.startsWith('https://') && !src.startsWith('data:') && !src.startsWith('blob:') && src.trim() !== '') {
      processedSrc = getImageUrl(src)
    }
    return `<img${before}src="${processedSrc}"${after}>`
  })
}

// 发布文章
const handlePublish = () => {
  try {
    if (!article.value.title.trim()) {
      message.warning('请先输入文章标题')
      return
    }

    if (!article.value.content.trim()) {
      message.warning('请先输入文章内容')
      return
    }

    // 重置发布表单
    publishForm.value.summary = ''
    publishForm.value.publishType = 'public'

    showPublishModal.value = true
  } catch (error) {
    console.error('发布文章时出错:', error)
    message.error('发布失败，请重试')
  }
}

const confirmPublish = async () => {
  publishing.value = true

  try {
    const url = isEdit.value ? `${API_BASE_URL}/articles/${route.params.id}` : `${API_BASE_URL}/articles`
    const method = isEdit.value ? 'PUT' : 'POST'

    const requestData = {
      title: article.value.title.trim(),
      content: article.value.content.trim(),
      summary: publishForm.value.summary.trim(),
      cover_image: article.value.coverImage,
      categories: article.value.categories,
      tags: article.value.tags
    }

    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getToken()}`
      },
      body: JSON.stringify(requestData)
    })
    const result = await response.json()

    if (result.code === 200) {
      message.success(isEdit.value ? '文章更新成功' : '文章发布成功')

      // 清除草稿
      const draftKey = isEdit.value ? `draft_edit_${route.params.id}` : 'draft_new_article'
      localStorage.removeItem(draftKey)

      // 跳转到文章详情页
      const articleId = isEdit.value ? route.params.id : result.data.id
      router.push(`/articles/${articleId}`)
    } else {
      message.error(result.msg || (isEdit.value ? '更新失败' : '发布失败'))
    }
  } catch (error) {
    console.error(isEdit.value ? '更新文章失败:' : '发布文章失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    publishing.value = false
    showPublishModal.value = false
  }
}

// 提取预览摘要
const extractPreviewSummary = () => {
  if (!article.value.content) return '暂无内容预览...'

  let text = article.value.content
    .replace(/```[\s\S]*?```/g, '')
    .replace(/`[^`]*`/g, '')
    .replace(/#{1,6}\s+/g, '')
    .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
    .replace(/!\[[^\]]*\]\([^)]+\)/g, '')
    .replace(/\*{1,2}([^*]+)\*{1,2}/g, '$1')
    .replace(/^>\s+/gm, '')
    .replace(/^[-*+]\s+/gm, '')
    .replace(/^\d+\.\s+/gm, '')
    .replace(/\n+/g, ' ')
    .replace(/\s+/g, ' ')
    .trim()

  return text.length > 100 ? text.substring(0, 100) + '...' : text
}

// 返回上一页
const handleBack = () => {
  if (article.value.title.trim() || article.value.content.trim()) {
    Modal.confirm({
      title: '确认离开',
      content: '当前有未保存的内容，确定要离开吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        router.back()
      }
    })
  } else {
    router.back()
  }
}

// 从草稿恢复
const loadDraft = () => {
  try {
    const draftKey = isEdit.value ? `draft_edit_${route.params.id}` : 'draft_new_article'
    const draftData = localStorage.getItem(draftKey)

    if (draftData) {
      const draft = JSON.parse(draftData)
      if (!isEdit.value || !article.value.title) {
        article.value = { ...draft }
        message.info('已恢复上次编辑的内容')
      }
    }
  } catch (error) {
    console.error('加载草稿失败:', error)
  }
}

// 已移除自动保存草稿功能

// 页面加载
onMounted(async () => {
  if (!userStore.isAuthenticated) {
    message.error('请先登录')
    router.push('/articles')
    return
  }

  // 设置页面标题
  document.title = isEdit.value ? '编辑文章' : '写文章'

  await fetchCategories()

  if (isEdit.value) {
    await fetchArticleDetail()
  } else {
    loadDraft()
  }
})
</script>

<style scoped>
.article-write {
  height: 100%;
  /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
  background-attachment: fixed;
  position: relative;
  overflow-y: scroll;
}

.article-write::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.write-container {
  margin: 0 auto;
  position: relative;
  margin-top: 20px;
  min-height: calc(100vh - 60px);
  padding-bottom: 100px;
  padding-left: 60px;
  padding-right: 60px;
}

.write-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
  background: rgba(255, 255, 255);
}

.write-header .ant-btn {
  border-radius: 12px;
  padding: 8px 20px;
  height: auto;
  font-weight: 500;
  transition: all 0.4s cubic-bezier(0.23, 1, 0.32, 1);
  position: relative;
  overflow: hidden;
}

.write-header .ant-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.write-header .ant-btn-primary {
  border: none;
  box-shadow: 0 8px 25px rgba(79, 172, 254, 0.3);
  position: relative;
  overflow: hidden;
}

.write-header .ant-btn-primary::before {
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
}

.header-center {
  flex: 1;
  text-align: center;
}

.draft-status {
  color: #fff;
  font-size: 15px;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  background: linear-gradient(135deg, rgba(82, 196, 26, 0.3) 0%, rgba(52, 199, 89, 0.3) 100%);
  padding: 10px 20px;
  border-radius: 25px;
  border: 1px solid rgba(82, 196, 26, 0.4);
  backdrop-filter: blur(15px);
  box-shadow: 0 4px 15px rgba(82, 196, 26, 0.2);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.02);
  }
}

.header-right {
  display: flex;
  gap: 16px;
}

.title-section {
  padding: 48px 48px 32px;
  background: rgba(250, 251, 252, 0.8);
  position: relative;
}

.title-input {
  font-size: 42px;
  font-weight: 800;
  line-height: 1.2;
  transition: all 0.4s cubic-bezier(0.23, 1, 0.32, 1);
  position: relative;
}

.title-input :deep(.ant-input) {
  font-size: 42px;
  font-weight: 800;
  padding: 16px 0;
  border: none;
  box-shadow: none;
  background: transparent;
  color: #1a202c;
  letter-spacing: -0.5px;
  transition: all 0.3s;
}

.title-input :deep(.ant-input:focus) {
  border: none;
  box-shadow: none;
  color: #2d3748;
}

.title-input :deep(.ant-input::placeholder) {
  background: linear-gradient(135deg, #a0aec0 0%, #718096 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 500;
  font-size: 42px;
}

.article-settings {
  padding: 20px;
  background: #fff;
}

.setting-item {
  margin-bottom: 0;
}

.setting-item label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  margin-bottom: 8px;
  letter-spacing: 0;
}

.setting-item .ant-select-focused {
  border-color: #4096ff;
  box-shadow: 0 0 0 2px rgba(64, 150, 255, 0.1);
}

/* 分类输入组样式 */
.category-input-group {
  display: flex;
  gap: 8px;
  align-items: stretch;
}

.category-input-group .ant-select {
  flex: 1;
}

/* 封面区域样式 */
.cover-section {
  width: 100%;
}

/* 封面上传按钮样式 */
.cover-upload-container {
  position: relative;
}

.cover-upload-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.2s;
  width: 100%;
  min-height: 80px;
}

.cover-upload-button:hover {
  border-color: #4096ff;
  background: #f0f8ff;
}

/* 封面预览区域样式 */
.cover-preview-section {
  width: 100%;
  display: flex;
  align-items: center;
}

.cover-preview-section .preview-image-container {
  position: relative;
  width: 164px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  margin-right: 30px;
  cursor: pointer;
  transition: all 0.2s;
}

.cover-preview-section .preview-image-container:hover {
  border-color: #4096ff;
  box-shadow: 0 2px 8px rgba(64, 150, 255, 0.2);
  transform: scale(1.02);
}

.cover-preview-section .preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.preview-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.preview-actions .preview-tips {
  font-size: 14px;
  color: #999;
  flex: 1;
  margin-left: 20px;
  display: inline-block;
}

.upload-icon {
  font-size: 16px;
  color: #666;
}

.upload-text {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.primary-text {
  font-size: 12px;
  font-weight: 500;
  color: #666;
}

.sub-text {
  font-size: 11px;
  color: #999;
  line-height: 1.2;
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 图片预览弹窗样式 */
.image-preview-container {
  text-align: center;
  padding: 20px 0;
}

.preview-full-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.cover-preview-card {
  display: flex;
  gap: 20px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(249, 250, 251, 0.95) 100%);
  border-radius: 16px;
  border: 1px solid rgba(228, 230, 234, 0.6);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.preview-image-container {
  position: relative;
  flex-shrink: 0;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.preview-image-container:hover {
}

.preview-image {
  width: 160px;
  height: 90px;
  object-fit: cover;
  display: block;
}

.image-overlay {
  position: absolute;
  top: 2px;
  right: 2px;
  opacity: 0;
  transition: opacity 0.2s;
}

.preview-image-container:hover .image-overlay {
  opacity: 1;
}

.remove-button {
  background: rgba(255, 77, 79, 0.9) !important;
  color: white !important;
  border: none !important;
  border-radius: 4px !important;
  padding: 2px 6px !important;
  font-size: 12px !important;
  height: auto !important;
}

.preview-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
}

.preview-label {
  font-size: 16px;
  font-weight: 700;
  color: #1a202c;
  display: flex;
  align-items: center;
  gap: 8px;
}

.preview-label::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  border-radius: 2px;
}

.preview-tips {
  font-size: 13px;
  color: #718096;
  line-height: 1.4;
  max-width: 200px;
}

.editor-section {
  padding: 0;
  position: relative;
}

.publish-settings {
  padding-top: 24px;
}

.article-preview h3 {
  margin: 32px 0 16px 0;
  font-size: 18px;
  font-weight: 700;
  color: #1d2129;
  display: flex;
  align-items: center;
  gap: 8px;
}

.article-preview h3::before {
  content: '';
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 2px;
}

.preview-card {
  padding: 24px;
  background: linear-gradient(135deg, #f7f8fa 0%, #ffffff 100%);
  border-radius: 12px;
  border: 1px solid #e4e6ea;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.preview-title {
  font-size: 20px;
  font-weight: 700;
  color: #1d2129;
  margin-bottom: 12px;
  line-height: 1.3;
}

.preview-summary {
  font-size: 15px;
  color: #515767;
  line-height: 1.6;
  margin-bottom: 16px;
}

.preview-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 13px;
  color: #8a919f;
  padding-top: 12px;
  border-top: 1px solid #e4e6ea;
}

.preview-meta span {
  position: relative;
  font-weight: 500;
}

.preview-meta span:not(:last-child)::after {
  content: '·';
  margin-left: 16px;
  color: #c9cdd4;
}

/* 编辑器样式覆盖 */
:deep(.md-editor) {
  border: none;
  box-shadow: 0 0 0 1px rgba(228, 230, 234, 0.5), 0 10px 25px rgba(0, 0, 0, 0.08);
  overflow: visible;
  backdrop-filter: blur(20px);
  height: auto;
  min-height: 800px;
}

:deep(.md-editor-content) {
  height: auto !important;
  overflow: visible !important;
}

:deep(.md-editor-input-wrapper),
:deep(.md-editor-preview-wrapper) {
  height: auto !important;
  overflow: visible !important;
}

:deep(.md-editor-input),
:deep(.md-editor-preview) {
  height: auto !important;
  min-height: 400px;
  overflow: visible !important;
  resize: none !important;
}

:deep(.md-editor-input-wrapper .textarea) {
  height: auto !important;
  min-height: 400px !important;
  resize: none !important;
  overflow: hidden !important;
}

/* 确保文本区域自动扩展 */
:deep(.md-editor-input) {
  field-sizing: content !important;
}

:deep(.md-editor-toolbar) {
  background: transparent;
  backdrop-filter: blur(20px);
}

:deep(.md-editor-toolbar-wrapper) {
  background: linear-gradient(135deg, rgba(247, 250, 252, 0.95) 0%, rgba(237, 242, 247, 0.95) 100%);
  padding: 8px;
  backdrop-filter: blur(10px);
}

:deep(.md-editor-toolbar-item) {
  border-radius: 10px;
  transition: all 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  padding: 8px 10px;
  margin: 2px;
  font-weight: 500;
}

:deep(.md-editor-toolbar-item:hover) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  transform: translateY(-1px) scale(1.02);
}

:deep(.md-editor-toolbar-item.active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

:deep(.md-editor-input-wrapper),
:deep(.md-editor-preview-wrapper) {
  padding: 16px;
  font-size: 18px;
  line-height: 1.8;
}

:deep(.md-editor-preview) {
  padding: 0;
}

:deep(.md-editor-input-wrapper) {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

:deep(.md-editor-preview-wrapper) {
  backdrop-filter: blur(10px);
  width: 50%;
}

:deep(.md-editor-input) {
  font-family: 'JetBrains Mono', 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Code', monospace;
  color: #2d3748;
  line-height: 1.8;
  font-size: 18px;
  font-weight: 500;
}

:deep(.md-editor-preview) {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Inter', 'Helvetica Neue', Arial, sans-serif;
  color: #1a202c;
  font-size: 18px;
  line-height: 1.8;
}

/* 预览区域图片样式 */
:deep(.md-editor-preview img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 16px 0;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.md-editor-preview h1),
:deep(.md-editor-preview h2),
:deep(.md-editor-preview h3) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 800;
}

:deep(.md-editor-preview blockquote) {
  border-left: 4px solid #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-radius: 0 8px 8px 0;
}

/* 发布弹窗样式 */
:deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

:deep(.ant-modal-header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  padding: 20px 24px;
}

:deep(.ant-modal-title) {
  color: #fff;
  font-weight: 600;
  font-size: 18px;
}

:deep(.ant-modal-close) {
  color: #fff;
}

:deep(.ant-modal-close:hover) {
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-modal-footer) {
  padding: 16px 24px;
  border-top: 1px solid #e4e6ea;
}

:deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #1d2129;
}

:deep(.ant-input),
:deep(.ant-input:focus),
:deep(.ant-radio-wrapper) {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .article-write {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .write-container {
    margin: 0;
    border-radius: 0;
    max-width: 100%;
  }

  .write-header {
    padding: 16px;
    flex-wrap: wrap;
    gap: 8px;
  }

  .header-center {
    order: 3;
    width: 100%;
    text-align: left;
    margin-top: 12px;
  }

  .header-right {
    gap: 8px;
  }

  .write-header .ant-btn {
    min-width: 80px;
    font-size: 13px;
    padding: 4px 12px;
  }

  .title-section {
    padding: 24px 20px 20px;
  }

  .title-input {
    font-size: 28px;
  }

  .title-input :deep(.ant-input) {
    font-size: 28px;
    padding: 8px 0;
  }

  .article-settings {
    padding: 16px;
  }

  /* 移动端垂直排列 */
  .article-settings .ant-row {
    flex-direction: column;
  }

  .article-settings .ant-col {
    width: 100% !important;
    margin-bottom: 12px;
  }

  .setting-item {
    margin-bottom: 16px;
  }

  /* 移动端封面预览调整 */
  .cover-preview-section .preview-image {
    height: 100px;
  }

  .preview-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .preview-actions .preview-tips {
    text-align: left;
  }

  :deep(.md-editor-toolbar) {
    padding: 8px 16px;
    flex-wrap: wrap;
  }

  :deep(.md-editor-input-wrapper),
  :deep(.md-editor-preview-wrapper) {
    padding: 16px 20px;
    font-size: 15px;
  }

  :deep(.md-editor-toolbar-item) {
    margin: 2px;
    font-size: 14px;
  }

  .preview-card {
    padding: 20px;
  }

  .preview-title {
    font-size: 18px;
  }

  .preview-summary {
    font-size: 14px;
  }

  .preview-meta {
    gap: 12px;
    flex-wrap: wrap;
  }

  :deep(.ant-modal) {
    margin: 16px;
  }

  :deep(.ant-modal-content) {
    margin: 0;
  }
}

@media (max-width: 480px) {
  .write-header {
    padding: 12px 16px;
  }

  .title-section {
    padding: 20px 16px;
  }

  .title-input {
    font-size: 24px;
  }

  .title-input :deep(.ant-input) {
    font-size: 24px;
  }

  .setting-item .ant-col {
    margin-bottom: 12px;
  }

  :deep(.md-editor-input-wrapper),
  :deep(.md-editor-preview-wrapper) {
    padding: 12px 16px;
    font-size: 14px;
  }
}
</style>
